<template>
  <div>
    <!-- 批量生成 2018/7/2 zhangQ -->
    <Form inline>
      <FormItem>
        <Select @on-change="changeDB" style="width: 200px">
          <template v-for="item in dbList">
            <Option :value="item.connName" :key="item.connName">{{ item.connName }}</Option>
          </template>
        </Select>
      </FormItem>

      <FormItem>
        <Select v-model="templatePath" style="width: 200px">
          <template v-for="item in templatePaths">
            <Option :value="item">{{ item }}</Option>
          </template>
        </Select>
      </FormItem>

      <FormItem>
        <Input v-model="tables.filterValue" placeholder="表名称过滤" clearable style="width: 200px"></Input>
      </FormItem>

      <FormItem>
        <Button type="primary" @click="staticTableRefFilter">过滤</Button>
        <Button type="primary" @click="checkConfig">选择配置</Button>
        <!--<Button type="primary" @click="staticTableRefCancelFilter">重置</Button>-->
        <!--&lt;!&ndash;<Button type="primary" @click="batchGeneration">生成</Button>&ndash;&gt;-->
      </FormItem>
    </Form>
    <!---->
    <staticTable :filterMethod="tableFilterMethod" ref="staticTableRef">
      <Table id="tableListBatch" ref="tableListRef" border :columns="tables.columns" :data="tables.data" highlight-row :height="tabHeight"></Table>
    </staticTable>

    <wtModal v-model="modalOpera.generationConfigShow" title="选择配置" className="vertical-center-modal" width="850px;">
      <generationConfig v-if="modalOpera.generationConfigShow" @close="modalOpera.checkConfigShow=false" @checkedConfig="checkedConfig"></generationConfig>
    </wtModal>
  </div>
</template>

<script>
  import initDb from '@/components/common/indexeddbUtil'
  import { queryTbaleObj, initTemplates } from '../components/generationUtil'
  import generationConfig from '../components/generationConfig'
  import _ from 'lodash'
  import mysqlDBHelpler from '@/components/common/mysqlDBHelper'
  import hw from '@/components/common/heightAndWidth'
  import wtModal from '@/components/wtModal'
  import { camelCaseName } from '@/components/common/utils'
  import staticTable from '@/components/staticTable'

  export default {
    name: 'index',
    data () {
      let dbList = []
      let modalOpera = { generationConfigShow: false }
      let tabHeight = 500
      let tables = {
        filterValue: '',
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            title: '表名',
            key: 'tableName'
            // render (h, params) {
            //   let checkBtn = (<i-input v-model={params.row.tableName}></i-input>)
            //   return ([checkBtn])
            // }
          },
          {
            title: 'tableComment',
            key: 'tableComment'
          },
          {
            title: '操作',
            render: (h, params) => {
              // let checkBtn = (<i-button type="primary" onClick={() => this.checkTable(params.row)}> 选择 </i-button>)
              let checkBtn = (<i-button type="primary"> 选择 </i-button>)
              return ([checkBtn])
            }
          }
        ],
        data: []
      }
      let templatePaths = ['snowFlake', 'default']
      let templatePath = 'snowFlake'
      let datas = { dbList, tables, tabHeight, modalOpera, templatePaths, templatePath }
      return datas
    },
    computed: {},
    methods: {
      /**
       * TODO(表格过滤方法)
       * @auther zhangQ
       * @date 2018/7/16 9:44
       */
      tableFilterMethod (row, index) {
        if (row.tableName && this.tables.filterValue) {
          // return
          return _.includes(row.tableName, this.tables.filterValue)
        }
        return true
      },
      /**
       * TODO(过滤tab)
       * @auther zhangQ
       * @date 2018/8/14 17:49
       */
      staticTableRefFilter () {
        this.$refs['staticTableRef'].customFilter()
        console.log('getCheckedData()', this.$refs['staticTableRef'].getCheckedData())
      },
      staticTableRefCancelFilter () {
        this.$refs['staticTableRef'].cancelCustomFilter()
      },
      test1 () {
        // this.$refs['tableListRef'].rebuildData = []
        console.log('tableListRef:tableListRef', this.$refs['tableListRef'])
        // console.log('tableListRef:objData', this.$refs['tableListRef'].rebuildData)
        // console.log('tableListRef:rebuildData', this.$refs['tableListRef'].rebuildData)
        // console.log('tableListRef:tableListRef', this.$refs['tableListRef'])
      },
      checkedConfig (generationForm) {
        // 开始批量生成
        this.batchGeneration(generationForm)
      },
      /**
       * 批量生成
       * generationForm:::生成配置
       */
      batchGeneration (generationForm) {
        this.$Spin.show()
        // console.log(this.$refs['tableListRef'])
        // 获取所有选中数据
        let resData = []
        // _.forIn(this.$refs['tableListRef'].objData, (val, key) => {
        //   if (val._isChecked) {
        //     resData.push(this.$refs['tableListRef'].rebuildData[key])
        //   }
        // })
        resData = this.$refs['staticTableRef'].getCheckedData()
        // 生成多个任务
        let funArray = []
        resData.forEach((item) => {
          funArray.push(new Promise((resolve, reject) => {
            queryTbaleObj(item.tableName)
              .then(res => {
                this.$store.dispatch('generation/setTables', [res])
                res.tableComment = item.tableComment
                resolve(res)
              })
              .catch(ex => {
                this.$Notice.error({
                  title: '获取表对象失败',
                  desc: ex
                })
                reject(ex)
              })
          }))
        })
        Promise.all(funArray)
          .then((res) => {
            this.$Notice.success({
              title: '读取成功'
            })
            this.$store.dispatch('generation/setTables', res)
            // 生成多个任务
            let filePromiseArr = []
            res.forEach((item) => {
              filePromiseArr.push(new Promise((resolve, reject) => {
                // 配置表头
                let generationFormParam = _.cloneDeep(generationForm)
                console.log('vtableal', item)
                generationFormParam.tableComment = item.tableComment
                generationFormParam.tableName = item.tableName
                generationFormParam.domainName = camelCaseName(item.tableName, true)
                let primaryKeyNameArray = []
                let primaryKeys = _.filter(item.columns, (o) => {
                  if (o.primaryKey) {
                    primaryKeyNameArray.push(o.name)
                  }
                  return o.primaryKey
                })
                if (primaryKeys && primaryKeys.length > 0) {
                  generationFormParam.primaryKey = primaryKeyNameArray.join(',')
                }
                this.startGeneration(generationFormParam, item)
                  .then((res1) => {
                    resolve(res1)
                  })
                  .catch(err => {
                    reject(err)
                  })
              }))
            })
            // 得到所有表数据了
            return Promise.all(filePromiseArr)
            // if (generationForm.utilsPackageName && generationForm.utilsPackageDir) {
            //   this.startUtilsGeneration(generationForm)
            // }
          })
          .then((res) => {
            this.$Notice.success({
              title: '写入成功！'
            })
            // 关闭弹窗
            this.modalOpera.generationConfigShow = false
          })
          .catch((res) => {
            console.log('res', res)
            this.$Notice.error({
              title: '写入失败',
              desc: res
            })
          })
          .finally((res) => {
            console.log('resKKKKKKKK', res)
            this.$Spin.hide()
          })
      },
      /**
       * TODO(开始生成文件)
       * @return result:::
       * @auther zhangQ
       * @date 2018/5/21 19:32
       */
      startGeneration (generationForm, tableInfo) {
        if (!generationForm.tableName || !generationForm.projectdir) {
          this.$Notice.warning({
            title: '请填写配置'
          })
          return
        }
        // 页面配置信息
        let configInfo = Object.assign({}, generationForm)
        configInfo.table = tableInfo
        // 模板文件配置
        let files = []
        if (generationForm.domainPackageDir) {
          files.push({
            name: 'domain',
            path: generationForm.projectdir + generationForm.domainPackageDir + '/',
            fileName: camelCaseName(generationForm.tableName, true) + '.java'
          })
        }
        if (generationForm.controllerPackageDir) {
          files.push({
            name: 'controller',
            path: generationForm.projectdir + generationForm.controllerPackageDir + '/',
            fileName: camelCaseName(generationForm.tableName, true) + 'Controller.java'
          })
        }
        if (generationForm.servicePackageDir) {
          files.push({
            name: 'service',
            path: generationForm.projectdir + generationForm.servicePackageDir + '/',
            fileName: camelCaseName(generationForm.tableName, true) + 'Service.java'
          })
          files.push({
            name: 'serviceImpl',
            path: generationForm.projectdir + generationForm.servicePackageDir + '/impl/',
            fileName: camelCaseName(generationForm.tableName, true) + 'ServiceImpl.java'
          })
        }
        if (generationForm.repositoryPackageDir) {
          files.push({
            name: 'repository',
            path: generationForm.projectdir + generationForm.repositoryPackageDir + '/',
            fileName: camelCaseName(generationForm.tableName, true) + 'Repository.java'
          })
        }
        if (generationForm.MapperPackageDir) {
          files.push({
            name: 'mapper',
            path: generationForm.projectdir + generationForm.MapperPackageDir + '/',
            fileName: camelCaseName(generationForm.tableName, true) + 'Mapper.java'
          })
        }
        if (generationForm.mybatisXmlDir) {
          files.push({
            name: 'mapperXML',
            path: generationForm.projectdir + generationForm.mybatisXmlDir + '/',
            fileName: camelCaseName(generationForm.tableName, true) + 'Mapper.xml'
          })
        }
        console.log('qwe', files)
        // 开始生成文件 一个文件一个任务，使用promise
        let funArray = []
        files.forEach((item) => {
          funArray.push(new Promise((resolve, reject) => {
            initTemplates(item, configInfo, this.templatePath)
              .then((res) => {
                resolve(res)
              })
              .catch((res) => {
                reject(res)
              })
          }))
        })
        return new Promise((resolve, reject) => {
          Promise.all(funArray)
            .then((res) => {
              // this.$Notice.success({
              //   title: '写入成功'
              // })
              resolve('写入成功')
            })
            .catch((res) => {
              console.log('res', res)
              this.$Notice.error({
                title: '写入失败',
                desc: res
              })
              reject(res)
            })
        })
      },
      /**
       * TODO(工具类生成)
       * @auther zhangQ
       * @date 2018/5/31 14:16
       */
      startUtilsGeneration (generationForm) {
        let files = [
          {
            name: 'utils/BaseController',
            path: generationForm.projectdir + generationForm.utilsPackageDir + '/',
            fileName: 'BaseController.java'
          },
          {
            name: 'utils/CamelMap',
            path: generationForm.projectdir + generationForm.utilsPackageDir + '/',
            fileName: 'CamelMap.java'
          }
        ] // 模板文件配置
        let funArray = []
        files.forEach((item) => {
          funArray.push(new Promise((resolve, reject) => {
            initTemplates(item, generationForm, this.templatePath)
              .then((res) => {
                resolve(res)
              })
              .catch((res) => {
                reject(res)
              })
          }))
        })
        Promise.all(funArray)
          .then((res) => {
            this.$Notice.success({
              title: '工具类写入成功'
            })
          })
          .catch((res) => {
            this.$Notice.error({
              title: '工具类写入失败',
              desc: res
            })
          })
      },
      changeDB (val) {
        // 清除选中行
        this.$refs['tableListRef'].clearCurrentRow()
        this.tables.data = []
        let config = _.find(this.dbList, { 'connName': String(val) })
        // console.log(config)database
        // 获得配置信息，查询数据
        mysqlDBHelpler.executeQuery('select * from INFORMATION_SCHEMA.`TABLES` where  table_schema=\'' + config.database + '\' ', config)
          .then(({ res, fields }) => {
            res.forEach((row) => {
              // TABLE_COMMENT    TABLE_NAME
              this.tables.data.push({ tableName: row['TABLE_NAME'], tableComment: row['TABLE_COMMENT'] })
            })
            this.$store.dispatch('generation/setDataSource', config)
          })
          .catch((ex) => {
            this.$Notice.error({
              title: '获取失败',
              desc: ex
            })
          })
      },
      // checkTable (row) {
      //   queryTbaleObj(row.tableName)
      //     .then(res => {
      //       this.$store.dispatch('generation/setTables', [res])
      //       this.$emit('close')
      //     })
      //     .catch(ex => {
      //       this.$Notice.error({
      //         title: '获取表对象失败',
      //         desc: ex
      //       })
      //       this.$emit('close')
      //     })
      // },
      /**
       * TODO(选择配置 )
       * @auther zhangQ
       * @date 2018/7/2 18:02
       */
      checkConfig () {
        this.modalOpera.generationConfigShow = true
      }
    },
    created () {
    },
    mounted () {
      setTimeout(() => {
        hw.setFullHeightAllWith('tableListBatch', 120, (height) => {
          this.tabHeight = height
        })
      }, 200)
      this.dbList = []
      let that = this
      initDb(contant.storeNames.connStore.name)
        .then((store) => {
          let cursor = store.openCursor()
          cursor.onsuccess = (e) => {
            let res = e.target.result
            if (res && res.value) {
              if (res.value.connName) {
                that.dbList.push(res.value)
              }
              res.continue()
              // 5-continue方法将光标移到下一个数据对象，如果当前数据对象已经是最后一个数据了，则光标指向null。
            }
          }
        })
    },
    components: { wtModal, generationConfig, staticTable }
  }
</script>

<style scoped>

</style>